package com.entrogy.controller;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiCspaceAddRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.response.OapiCspaceAddResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.entrogy.bean.*;
import com.entrogy.config.Constant;
import com.entrogy.config.Result;
import com.entrogy.config.URLConstant;
import com.entrogy.service.*;
import com.entrogy.utils.AccessTokenUtil;
import com.entrogy.utils.DateUtils;
import com.entrogy.utils.ServiceResult;
import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 许红松
 * @date 2019/5/7 0007 上午 9:14
 * E应用接口
 */
@Api(description = "E应用操作接口")
@RestController
@RequestMapping(value = "/")
public class EapplyController {


    @Autowired
    private UserService userService;//用户管理service接口

    @Autowired
    private AppraisalService appraisalService;//考勤管理service接口
    @Autowired
    private CheckTimeService checkTimeService;//
    @Autowired
    private BorrowBookService borrowBookService;//图书借阅service 接口
    @Autowired
    private StudentService studentService;//学生管理service接口
    @Autowired
    private QuotaSuperviseService quotaSuperviseService;//额度管理service接口
    @Autowired
    private ConsumeListService consumeListService;//花费或充值流水service接口

    /**
     * 欢迎页面,通过url访问，判断后端服务是否启动
     */
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String welcome() {
        return "welcome";
    }


    /**
     * 获取accessToken
     *
     * @return
     */
    public String getaccessToken(HttpServletRequest request) {

        String accessToken = "";
        if (request.getSession(false).getAttribute("accessToken") != null) {
            accessToken = request.getSession().getAttribute("accessToken").toString();
        } else {
            accessToken = AccessTokenUtil.getToken();
            request.getSession(false).setAttribute("accessToken", accessToken);
        }
        return accessToken;
    }

    /**
     * 钉钉用户登录，显示当前登录用户的userId和名称
     *
     * @param requestAuthCode 免登临时code
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult login(@RequestParam(value = "requestAuthCode") String requestAuthCode, HttpServletRequest request) {
        String requestAuthCode1 = requestAuthCode.substring(1, requestAuthCode.length() - 1);
       /* System.out.println("accessToken:"+accessToken);
        */
        /*System.out.println("requestAuthCode:"+requestAuthCode);
        System.out.println("requestAuthCode:"+requestAuthCode.substring(1, requestAuthCode.length() - 1));
        System.out.println("requestAuthCode:"+requestAuthCode.substring(2, requestAuthCode.length() - 2));*/
        //获取用户信息
        DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_GET_USER_INFO);
        OapiUserGetuserinfoRequest request1 = new OapiUserGetuserinfoRequest();
        request1.setCode(requestAuthCode1);
        request1.setHttpMethod("GET");
        OapiUserGetuserinfoResponse response;
        //获取accessToken,注意正是代码要有异常流处理
        String accessToken = getaccessToken(request);

        try {
            response = client.execute(request1, accessToken);
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
        //3.查询得到当前用户的userId
        // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验
        String userId = response.getUserid();
        /* System.out.println("userId:"+userId);*/
        String userName = getUserName(accessToken, userId);

        /* System.out.println(userName);*/
        //返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userId", userId);
        resultMap.put("userName", userName);
        ServiceResult serviceResult = ServiceResult.success(resultMap);
        request.getSession().setAttribute("userId", userId);
        request.getSession().setAttribute("userName", userName);
        return serviceResult;
    }


    /**
     * 获取用户姓名
     *
     * @param accessToken
     * @param userId
     * @return
     */
    private String getUserName(String accessToken, String userId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_USER_GET);
            OapiUserGetRequest request = new OapiUserGetRequest();
            request.setUserid(userId);
            request.setHttpMethod("GET");
            OapiUserGetResponse response = client.execute(request, accessToken);
            return response.getName();
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据用户id  查询考勤数据
     *
     * @param personId
     * @return
     */
    @RequestMapping(value = "/getAppraisalByList", method = RequestMethod.POST)
    public List<Appraisal> getAppraisalByList(String beginDates, String endDates, String personId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userService.getUserById(personId);
        if (beginDates != null && !"".equals(beginDates)) {
            map.put("beginDates", beginDates);
        } else {
            map.put("beginDates", DateUtils.GetNowDate2());
        }
        if (endDates != null && !"".equals(endDates)) {
            map.put("endDates", endDates);
        }
        map.put("school_code", userEntity.getSchoolCode());
        if (personId != null && !"".equals(personId)) {
            map.put("personId", personId);
        }
        map.put("school_code","510104000");
        List<Appraisal> list = appraisalService.getAppraisalByList(map);
        return list;
    }


    /**
     * 根据考勤id  查询考勤数据详情
     *
     * @param appraisalId
     * @return
     */
    @RequestMapping(value = "/selectAppraisalById", method = RequestMethod.POST)
    public Result selectAppraisalById(String appraisalId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        if (appraisalId != null && !"".equals(appraisalId)) {
            map.put("appraisalId", appraisalId);
        }
        if (request.getSession().getAttribute("userId") != null) {
            UserEntity userEntity = userService.getUserById(request.getSession().getAttribute("userId").toString());
            if (userEntity != null) {
                map.put("school_code", userEntity.getSchoolCode());
            }
        }
        map.put("school_code","510104000");
        Appraisal appraisal = appraisalService.selectAppraisalById(map);
        Result result;
        if (appraisal != null) {
            result = new Result().getResult(401, "查询成功", 1, appraisal);
        } else {
            result = new Result().getResult(403, "查询失败", 2, null);
        }
        return result;
    }




   /* @PostMapping(value = "/get_custom_space")
    public  Result   get_custom_space(){
        DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_CUSTOM_GET);
        OapiCspaceGetCustomSpaceRequest request = new OapiCspaceGetCustomSpaceRequest();
        request.setAgentId(Constant.APP_AGGENTID);
        request.setDomain("test");
        request.setHttpMethod("GET");
        OapiCspaceGetCustomSpaceResponse response = client.execute(request,accessToken);
    }*/

    /**
     * 上传文件
     *
     *
     * @param Code        如果是微应用，code值为微应用免登授权码
     * @param media_id    调用钉盘上传文件接口得到的mediaid，需要utf-8 urlEncode
     * @param space_id    调用钉盘选择控件后获取的用户钉盘空间ID
     * @param folder_id   调用钉盘选择控件后获取的用户钉盘文件夹ID
     * @param name        上传文件的名称，不能包含非法字符，需要utf-8 urlEncode
     * @return
     */
    @PostMapping(value = "/Uploadfiles")
    public OapiCspaceAddResponse Uploadfiles(String Code, String media_id, String space_id, String folder_id, String name) {
        DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_UPLOADFILE_GET);
        String accessToken = AccessTokenUtil.getToken();
        OapiCspaceAddRequest request = new OapiCspaceAddRequest();
        request.setAgentId(Constant.APP_AGGENTID);
        request.setCode(Code);
        request.setMediaId(media_id);
        request.setSpaceId(space_id);
        request.setFolderId(folder_id);
        request.setName(name);
        request.setOverwrite(true);
        request.setHttpMethod("GET");
        OapiCspaceAddResponse response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }

        return response;
    }

    /**
     * 查询学生成绩
     *
     * @return
     */
    @GetMapping(value = "/getScoreList")
    public List<Map<String, Object>> getScoreList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("exam_id", "29");
        if (request.getSession().getAttribute("userId")!=null){
            String userId=request.getSession().getAttribute("userId").toString();
            /*StudentEntity studentEntity=studentService.getStudentById(Integer.parseInt(userId));*/
           // map.put("userId", userId);

           /* }*/
        }
        String m="110010";

        map.put("yuwenId",m.concat("1"));
        map.put("shuxueId",m.concat("2"));
        map.put("yingyuId",m.concat("3"));
        map.put("wuliId",m.concat("4"));
        map.put("huaxueId",m.concat("5"));
        map.put("shengwuId",m.concat("6"));
        map.put("school_code","510104000");
        checkTimeService.getScoreList(map);
        return checkTimeService.getScoreList(map);
    }

    /**
     * 发送
     *
     * @return
     */
    @PostMapping(value = "/asyncsend")
    public OapiMessageCorpconversationAsyncsendV2Response asyncsend(String UserId1, String UserName, HttpServletRequest requests) {
        String accessToken = getaccessToken(requests);
        DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_ASYNCSEND_POST);
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setUseridList(UserId1);
        request.setAgentId(Long.parseLong(Constant.APP_AGGENTID));
        request.setToAllUser(false);
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
       /*  msg.setMsgtype("text");
         msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
         msg.getText().setContent("test123");
         request.setMsg(msg);*/

         /*msg.setMsgtype("image");
         msg.setImage(new OapiMessageCorpconversationAsyncsendV2Request.Image());
         msg.getImage().setMediaId("@lADOdvRYes0CbM0CbA");
         request.setMsg(msg);

         msg.setMsgtype("file");
         msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
         msg.getFile().setMediaId("@lADOdvRYes0CbM0CbA");
         request.setMsg(msg);*/

       /*  msg.setMsgtype("link");
         msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
         msg.getLink().setTitle("test");
         msg.getLink().setText("test");
         msg.getLink().setMessageUrl("test");
         msg.getLink().setPicUrl("test");
         request.setMsg(msg);

         msg.setMsgtype("markdown");
         msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
         msg.getMarkdown().setText("##### text");
         msg.getMarkdown().setTitle("### Title");
         request.setMsg(msg);*/

         /*msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
         msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
         msg.getOa().getHead().setText("head");
         msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
         msg.getOa().getBody().setContent("xxx");
         msg.setMsgtype("oa");
         request.setMsg(msg);*/

        msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());
        msg.getActionCard().setTitle("成绩第五次测试");
        msg.getActionCard().setMarkdown("### 测试时间");
        msg.getActionCard().setSingleTitle("点击详情查看详情");
        String path = requests.getContextPath();
        String basePath = requests.getScheme() + "://" + requests.getServerName() + ":" + requests.getServerPort() + path + "/";
        msg.getActionCard().setSingleUrl(basePath + "getScoreList?userId=1");
        msg.setMsgtype("action_card");
        request.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response response = null;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }

        return response;
    }

    /**
     * 图书管理
     * @param request
     * @return
     */
    @PostMapping(value = "/getBorrowBookList")
    public List<BorrowBookEntity> getBorrowBookList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        if (request.getSession().getAttribute("userId") != null) {
            String UserId=request.getSession().getAttribute("userId").toString();
            UserEntity userEntity = userService.getUserById(UserId);
            map.put("borrowId",userEntity.getId());
            if (userEntity != null) {
                map.put("school_code", userEntity.getSchoolCode());
            }
        }
        map.put("school_code","510104000");
        return borrowBookService.getBorrowBookList(map);
    }

    /**
     * 查询详情
     * @return
     */
    @PostMapping(value = "/getBorrowBookById")
    public  BorrowBookEntity getBorrowBookById(String  id){

        return borrowBookService.getBorrowBookByid(id);
    }    /**
     * 查询消费的所有信息
     * @param request
     * @return
     */
    @PostMapping(value = "/getQuotaSuperviseList")
    public List<QuotaSuperviseEntity>  getQuotaSuperviseList(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
      /*  if (request.getSession().getAttribute("userId") != null) {
            String UserId=request.getSession().getAttribute("userId").toString();
            UserEntity userEntity = userService.getUserById(UserId);
          //  map.put("UserId",userEntity.getId());
            if (userEntity != null) {
                map.put("school_code", userEntity.getSchoolCode());
            }
        }*/
        map.put("school_code","510104000");
        return quotaSuperviseService.getQuotaSuperviseList(map);
   }

    /**
     * 某人的消费流水
     * @param request
     * @param id
     * @return
     */
    @PostMapping(value = "/getConsumeList")
    public List<ConsumeListEntity>  getConsumeList(HttpServletRequest request,int id,int stype){
        Map<String, Object> map = new HashMap<>();
        if (request.getSession().getAttribute("userId") != null) {
            String UserId=request.getSession().getAttribute("userId").toString();
            UserEntity userEntity = userService.getUserById(UserId);
            //  map.put("UserId",userEntity.getId());
            if (userEntity != null) {
                map.put("school_code", userEntity.getSchoolCode());
            }
        }
        map.put("id",id);
        map.put("Type",stype);
        return consumeListService.getConsumeList(map);
    }

    /**
     * 查询单挑信息详情
     * @param id
     * @return
     */
    @PostMapping(value = "/getConsumeById")
    public ConsumeListEntity  getConsumeById(String   id){
        return consumeListService.getConsumeListById(id);
    }
}
